<template>
  <div class="doc-sidebar">
    <div class="sidebar-header">
      <h3>{{ currentSpace.FTitle }}</h3>
      <el-tag size="small">{{ currentSpace.FTag }}</el-tag>
    </div>

    <div class="search-box">
      <el-input v-model="filterText" placeholder="搜索文档" size="small" clearable />
    </div>

    <!-- 新建根节点按钮（带下拉菜单） -->
    <div class="new-root-btn">
      <el-dropdown @command="handleNewRootCommand" trigger="click" v-if="isAdmin">
        <el-button type="primary" size="small">
          <el-icon><Plus /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="new-folder" :icon="Folder">新建文件夹</el-dropdown-item>
            <el-dropdown-item command="new-doc" :icon="Document">新建文档</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="docTree"
        :props="treeProps"
        :filter-node-method="filterNode"
        node-key="FId"
        highlight-current
        :expand-on-click-node="false"
        :current-node-key="currentDocId"
        :default-expand-all="expandAll"
        v-loading="loading"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="tree-node">
            <el-icon v-if="data.FType === 'folder' && isAdmin" data-type="folder"><Folder /></el-icon>
            <el-icon v-else-if="data.FType === 'doc' && isAdmin" data-type="doc"><Document /></el-icon>
            <span class="node-title">{{ node.label }}</span>
            <span v-if="data.isNew" class="new-badge">NEW</span>

            <!-- 节点操作按钮 -->
            <span class="node-actions" @click.stop v-if="isAdmin">
              <el-dropdown trigger="click" @command="command => handleCommand(command, data)">
                <el-icon class="more-btn"><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <template v-if="data.FType === 'folder'">
                      <el-dropdown-item command="new-folder" :icon="Folder">新建文件夹</el-dropdown-item>
                      <el-dropdown-item command="new-doc" :icon="Document">新建文档</el-dropdown-item>
                    </template>
                    <el-dropdown-item command="permission" :icon="Edit">权限</el-dropdown-item>
                    <el-dropdown-item command="rename" :icon="Edit">重命名</el-dropdown-item>
                    <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineProps, defineEmits } from "vue";
import { Folder, Document, Plus, MoreFilled, Edit, Delete } from "@element-plus/icons-vue";
import type { Space } from "@/api/interface/space";
import type { Doc } from "@/api/interface/doc";
import type { TreeNodeData } from "element-plus/es/components/tree/src/tree.type";

const props = withDefaults(
  defineProps<{
    currentSpace: Space.SpaceItem;
    docTree: Doc.DocNode[];
    currentDocId?: string;
    loading: boolean;
    expandAll?: boolean;
    isAdmin: boolean;
  }>(),
  {
    expandAll: true // ✅ 给 expandAll 设置默认值
  }
);

const emit = defineEmits<{
  (e: "selectNode", node: Doc.DocNode): void;
  (e: "newRoot", payload: { type: Doc.DocType }): void;
  (e: "newNode", payload: { parentId: string; type: Doc.DocType }): void;
  (e: "renameNode", node: Doc.DocNode): void;
  (e: "deleteNode", node: Doc.DocNode): void;
  (e: "permission", node: Doc.DocNode): void;
}>();

const filterText = ref("");
const treeRef = ref();
const treeProps = {
  children: "children",
  label: "FTitle"
};

watch(filterText, val => {
  treeRef.value?.filter(val);
});

const filterNode = (value: string, data: TreeNodeData): boolean => {
  if (!value) return true;
  const nodeData = data as Doc.DocNode;
  return nodeData.FTitle.toLowerCase().includes(value.toLowerCase());
};

const handleNodeClick = (node: Doc.DocNode) => {
  emit("selectNode", node);
};

const handleCommand = (command: string, data: Doc.DocNode) => {
  switch (command) {
    case "new-doc":
      emit("newNode", { parentId: data.FId, type: "doc" });
      break;
    case "new-folder":
      emit("newNode", { parentId: data.FId, type: "folder" });
      break;
    case "rename":
      emit("renameNode", data);
      break;
    case "delete":
      emit("deleteNode", data);
      break;
    case "permission":
      emit("permission", data);
      break;
  }
};

const handleNewRootCommand = (command: string) => {
  switch (command) {
    case "new-doc":
      emit("newRoot", { type: "doc" });
      break;
    case "new-folder":
      emit("newRoot", { type: "folder" });
      break;
  }
};

// ✅ 如果需要动态控制全部展开/收起，可以监听 props.expandAll
watch(
  () => props.expandAll,
  newVal => {
    if (!treeRef.value) return;
    if (newVal) {
      // 全部展开
      expandAllNodes();
    } else {
      // 全部收起
      collapseAllNodes();
    }
  }
);

const expandAllNodes = () => {
  const tree = treeRef.value;
  if (tree) {
    tree.store.nodesMap &&
      Object.values(tree.store.nodesMap).forEach((node: any) => {
        node.expanded = true;
      });
  }
};

const collapseAllNodes = () => {
  const tree = treeRef.value;
  if (tree) {
    tree.store.nodesMap &&
      Object.values(tree.store.nodesMap).forEach((node: any) => {
        node.expanded = false;
      });
  }
};

// 初始化时根据 expandAll 控制
onMounted(() => {
  if (props.expandAll) {
    expandAllNodes();
  }
});
</script>

<style scoped>
/* 原有样式保持不变，只添加下拉按钮样式 */
.new-root-btn .el-dropdown {
  width: 100%;
}
.new-root-btn .el-button {
  width: 100%;
}

/* 其他原有样式... */
.doc-sidebar {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
  min-width: 280px;
  height: 100%;
  background-color: #ffffff;
  border-right: 1px solid #e1e4e8;
  box-shadow: 1px 0 4px rgb(0 0 0 / 5%);
}
.sidebar-header {
  padding: 18px 20px 14px;
  border-bottom: 1px solid #f0f2f5;
}
.sidebar-header h3 {
  margin: 0 0 8px;
  overflow: hidden;
  font-size: 16px;
  font-weight: 600;
  color: #24292e;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sidebar-header .el-tag {
  font-weight: 500;
  color: #1a73e8;
  background-color: #f0f7ff;
  border-color: #d0e3ff;
}
.search-box {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f2f5;
}
.search-box :deep(.el-input__wrapper) {
  background-color: #f6f8fa;
  border-radius: 6px;
  box-shadow: 0 0 0 1px #e1e4e8 inset;
}
.search-box :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #d0d7de inset;
}
.search-box :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #2188ff inset;
}
.new-root-btn {
  padding: 8px 16px;
  border-bottom: 1px solid #f0f2f5;
}
.tree-container {
  flex: 1;
  padding: 8px 0;
  overflow-y: auto;
}
:deep(.el-tree) {
  background-color: transparent;

  --el-tree-node-hover-bg-color: #f6f8fa;
  --el-tree-text-color: #24292e;
}
:deep(.el-tree-node__content) {
  height: 36px;
  padding-right: 16px;
  transition: background-color 0.2s ease;
}
:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #f6f8fa;
}
:deep(.el-tree-node__content:hover) {
  background-color: #f6f8fa;
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  font-weight: 500;
  color: #1a73e8;
  background-color: #e8f4ff;
}
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  font-size: 14px;
}
.tree-node .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #6a737d;
}
.tree-node .el-icon[data-type="folder"] {
  color: #54a3ff;
}
.tree-node .el-icon[data-type="doc"] {
  color: #6a737d;
}
.node-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.new-badge {
  padding: 2px 6px;
  margin-left: 8px;
  font-size: 12px;
  font-weight: 500;
  color: #0366d6;
  background-color: #f1f8ff;
  border-radius: 12px;
}
.node-actions {
  display: none;
  margin-left: 8px;
}
.more-btn {
  padding: 4px;
  color: #6a737d;
  cursor: pointer;
  border-radius: 4px;
}
.more-btn:hover {
  background-color: #e1e4e8;
}
:deep(.el-tree-node__content:hover) .node-actions {
  display: block;
}
.tree-container::-webkit-scrollbar {
  width: 6px;
}
.tree-container::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}
.tree-container::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}
</style>
